import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;


public class ChatApp {

	final static int PUERTO_CHAT1 = 5000;
	final static int PUERTO_CHAT2 = 6000;
	final static String HOST = "localhost";
	
	public static ServerSocket creaSocketServidor(int puerto) {
		
		ServerSocket sSocket = null;
		
		try {
			sSocket = new ServerSocket(puerto);
		} catch (IOException e) {
			System.err.println(e.getMessage());
			e.printStackTrace();
		}
		
		return sSocket;				
	}
	
	
	/**
	 * @param args
	 * @throws IOException 
	 */
	public static void main(String[] args) throws IOException {

		ServerSocket sSocket;
		Socket cSocket;
			
		int puertoServidor = PUERTO_CHAT1;
		int puertoCliente = PUERTO_CHAT2;
		
		DataInputStream dis = null;
		DataOutputStream dos = null;
		String msg = null;
		Scanner sc = new Scanner(System.in);
		
		sSocket = creaSocketServidor(puertoServidor);	
		if (sSocket == null) {
			puertoServidor = PUERTO_CHAT2;
			puertoCliente = PUERTO_CHAT1;
			sSocket = creaSocketServidor(puertoServidor);
		}		
		if (sSocket == null) {
			System.err.println("No se puede crear el socket servidor");
			System.exit(1);
		}		
		System.out.println("Escuchando en el puerto "+puertoServidor);

		cSocket = null;


		if (puertoServidor == PUERTO_CHAT2) {
			cSocket = new Socket(HOST, puertoCliente);			
			System.out.print("Mensaje: ");
			dos = new DataOutputStream(cSocket.getOutputStream());
			dos.writeUTF(sc.nextLine());
		}
		
		
		do {
			
			Socket rSocket = sSocket.accept();
			dis = new DataInputStream(rSocket.getInputStream());
			msg = dis.readUTF();
			System.out.println(msg);
			
			if (cSocket == null) {
				cSocket = new Socket(HOST, puertoCliente);
				dos = new DataOutputStream(cSocket.getOutputStream());
			}
			
			if (msg.equalsIgnoreCase("FIN"))
				dos.writeUTF("FIN");
			else {			
				System.out.print("Mensaje: ");
				dos.writeUTF(sc.nextLine());
			}
			rSocket.close();
			
		} while (!msg.equalsIgnoreCase("FIN"));
		
		sSocket.close();		
	}
	

}
